<template>
  <div class="app-container">
    <div class="smart-lock-container" v-for="(lock, index) in smartlocksList" :key="index" v-loading="loading">
      <!-- 智能锁信息卡片 -->
      <div class="lock-card">
        <!-- 锁信息头部 -->
        <div class="lock-header">
          <div class="lock-icon-wrapper">
            <div class="lock-icon">
              <i class="el-icon-unlock"></i>
              <div class="lock-icon-inner">
                <i class="el-icon-lock"></i>
              </div>
            </div>
            <!-- <div class="lock-status-indicator" :class="isOnline(lock) ? 'online' : 'offline'"></div> -->
          </div>
          <div class="lock-title">
            <span class="device-name">智能门锁</span>
            <!-- <div class="device-info">
              <span class="device-mac">MAC: {{lock.mac}}</span>
              <el-tag
                :type="isOnline(lock) ? 'success' : 'danger'"
                size="mini"
                effect="plain"
                class="status-tag"
              >
                {{ isOnline(lock) ? '在线' : '离线' }}
              </el-tag>
            </div> -->
          </div>
          <div class="header-actions">
            <el-tooltip content="刷新信息" placement="top">
              <el-button
                type="text"
                icon="el-icon-refresh"
                @click="refreshLockInfo(lock)"
                class="refresh-btn"
                :class="{'rotate': refreshing}"
              ></el-button>
            </el-tooltip>
          </div>
        </div>

        <!-- 基本信息展示区 -->
        <div class="lock-info-content">
          <div class="info-section">
            <!-- 电量信息卡片 -->
            <div class="metric-card battery-card" :class="getBatteryColorClass(lock.batteryLevel)">
              <div class="metric-icon-wrapper">
                <i class="el-icon-lightning metric-icon"></i>
              </div>
              <div class="metric-content">
                <div class="metric-title">电量</div>
                <div class="metric-value-wrapper">
                  <battery :capacity="lock.batteryLevel" class="battery-indicator"></battery>
                <!--  <span class="metric-value">{{lock.batteryLevel}}%</span> -->
                </div>
              </div>
            </div>

            <!-- 信号强度卡片 -->
            <!-- <div class="metric-card signal-card">
              <div class="metric-icon-wrapper">
                <i class="el-icon-connection metric-icon"></i>
              </div>
              <div class="metric-content">
                <div class="metric-title">信号强度</div>
                <div class="metric-value-wrapper">
                  <signal-strength :value="lock.rssi" />
                  <span class="metric-value">{{lock.rssi}} dBm</span>
                </div>
              </div>
            </div> -->

            <!-- 电池电压卡片 -->
            <!-- <div class="metric-card voltage-card">
              <div class="metric-icon-wrapper">
                <i class="el-icon-cpu metric-icon"></i>
              </div>
              <div class="metric-content">
                <div class="metric-title">电池电压</div>
                <div class="metric-value">{{lock.volt || '0'}} mV</div>
              </div>
            </div> -->
          </div>

          <div class="info-divider">
            <span class="divider-text">设备详情</span>
          </div>

          <div class="details-grid" :class="{'expanded': showAdvanced}">
            <!-- 心跳间隔 -->
            <!-- <div class="detail-item">
              <div class="detail-icon"><i class="el-icon-timer"></i></div>
              <div class="detail-content">
                <div class="detail-label">心跳间隔</div>
                <div class="detail-value">{{lock.hbinterval || '未设置'}}</div>
              </div>
            </div> -->

            <!-- 通讯时间 -->
            <div class="detail-item">
              <div class="detail-icon"><i class="el-icon-time"></i></div>
              <div class="detail-content">
                <div class="detail-label">最后通讯时间</div>
                <div class="detail-value">{{formatTime(lock.lastCommunication)}}</div>
              </div>
            </div>

            <!-- 管理员密码 -->
           <!-- <div class="detail-item">
              <div class="detail-icon"><i class="el-icon-key"></i></div>
              <div class="detail-content">
                <div class="detail-label">管理员密码(PWD)</div>
                <div class="detail-value pwd-value">
                  <template v-if="lock.pwd">
                    <span v-if="showPwd">{{ lock.pwd }}</span>
                    <span v-else>••••••</span>
                    <el-button
                      type="text"
                      size="mini"
                      class="toggle-pwd-btn"
                      @click="showPwd = !showPwd"
                    >
                      {{ showPwd ? '隐藏' : '查看' }}
                    </el-button>
                  </template>
                  <span v-else>未设置</span>
                </div>
              </div>
            </div> -->

            <!-- 版本信息 (如有) -->
            <!-- <div class="detail-item" v-if="lock.firmwareVersion">
              <div class="detail-icon"><i class="el-icon-s-platform"></i></div>
              <div class="detail-content">
                <div class="detail-label">固件版本</div>
                <div class="detail-value">{{lock.firmwareVersion}}</div>
              </div>
            </div> -->

            <!-- 硬件版本 (如有) -->
            <!-- <div class="detail-item" v-if="lock.hardwareVersion">
              <div class="detail-icon"><i class="el-icon-s-operation"></i></div>
              <div class="detail-content">
                <div class="detail-label">硬件版本</div>
                <div class="detail-value">{{lock.hardwareVersion}}</div>
              </div>
            </div> -->

            <!-- 通信协议 (如有) -->
            <!-- <div class="detail-item" v-if="lock.protocol">
              <div class="detail-icon"><i class="el-icon-connection"></i></div>
              <div class="detail-content">
                <div class="detail-label">通信协议</div>
                <div class="detail-value">{{lock.protocol}}</div>
              </div>
            </div> -->

            <!-- 其他可能的设备信息占位符 -->
            <!-- <div class="detail-item" v-if="showAdvanced && false">
              <div class="detail-icon"><i class="el-icon-info"></i></div>
              <div class="detail-content">
                <div class="detail-label">其他信息</div>
                <div class="detail-value">暂无数据</div>
              </div>
            </div> -->
          </div>

          <!-- 操作按钮区 -->
          <div class="lock-actions">
            <div class="advanced-toggle" @click="toggleAdvanced">
              <span>{{ showAdvanced ? '收起详情' : '显示更多' }}</span>
              <i :class="[showAdvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
            </div>
            <div class="buttons-row">
             <!-- <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
				v-hasPermi="['lock:smartlocks:clear']"
                @click="confirmClearPassword"
                class="action-btn danger-btn"
              >清除密码</el-button>
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
				v-hasPermi="['lock:smartlocks:clear']"
                @click="confirmClearCard"
                class="action-btn danger-btn"
              >清除卡片</el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-key"
                @click="hxAddSingleKeyHandel"
                class="action-btn"
              >一次性密码</el-button>
              <el-button
                type="success"
                size="small"
                icon="el-icon-date"
                @click="showPeriodPasswordDialog"
                class="action-btn"
              >周期性密码</el-button> -->

              <!-- 远程开门按钮 -->
              <el-button
                type="success"
                size="small"
                icon="el-icon-key"
				v-hasPermi="['lock:smartlocks:yckm']"
                @click="handleRemoteOpen(lock)"
                class="action-btn"
              >远程开门</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 周期性密码对话框 -->
    <el-dialog
      :visible.sync="periodDialogVisible"
      width="720px"
      :before-close="handleClose"
      :show-close="false"
      center
      class="password-dialog-wrapper"
      top="15vh"
    >
      <div slot="title" class="custom-dialog-title">
        <i class="el-icon-date"></i>
        <span>周期性密码</span>
      </div>
      <div class="password-dialog">
        <!-- 密码列表 -->
        <div v-if="periodPasswords.length > 0" class="period-passwords-list">
          <div class="section-header">
            <h4 class="section-title">已有密码</h4>
            <el-switch
              v-model="showExpiredPasswords"
              active-text="显示过期密码"
              inactive-text="隐藏过期密码"
              @change="refreshPeriodicPasswords"
            ></el-switch>
          </div>
          <el-table
            :data="periodPasswords"
            style="width: 100%"
            :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
            border
            size="small"
            max-height="250"
          >
            <el-table-column prop="password" label="密码" width="100" align="center" />
            <el-table-column label="有效期" width="250">
              <template slot-scope="scope">
                <span v-if="scope.row.startTime && scope.row.endTime">
                  {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
                </span>
                <span v-else>无效日期</span>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注">
              <template slot-scope="scope">
                <el-input
                  v-if="scope.row.editing"
                  v-model="scope.row.remarks"
                  size="mini"
                  placeholder="请输入备注"
                  @blur="saveRemarks(scope.row)"
                ></el-input>
                <div v-else @click="startEdit(scope.row)" class="editable-cell">
                  {{ scope.row.remarks || '点击添加备注' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isExpired ? 'danger' : 'success'" size="mini">
                  {{ scope.row.isExpired ? '已过期' : '有效' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <div class="divider-line"></div>
        </div>

        <!-- 生成新密码表单 -->
        <div v-if="!periodPassword" class="period-form">
          <h4 class="section-title">生成新密码</h4>
          <el-form :model="periodForm" label-width="100px" size="small" :rules="periodFormRules" ref="periodForm">
            <div class="time-selection-area">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                      v-model="periodForm.startTime"
                      type="datetime"
                      placeholder="选择开始时间"
                      value-format="yyyy-MM-dd'T'HH:mm:ss"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                      v-model="periodForm.endTime"
                      type="datetime"
                      placeholder="选择结束时间"
                      value-format="yyyy-MM-dd'T'HH:mm:ss"
                      style="width: 100%"
                    ></el-date-picker>
                    <div class="form-tip">结束时间必须比开始时间至少晚1小时</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="periodForm.remarks"
                placeholder="请输入备注信息（可选）"
                clearable
              ></el-input>
            </el-form-item>

            <el-form-item class="form-buttons">
              <el-button type="primary" @click="generatePeriodPassword" :loading="periodLoading" size="medium">生成密码</el-button>
              <el-button @click="periodDialogVisible = false" size="medium">取消</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 显示新生成的密码 -->
        <div v-if="periodPassword" class="generated-password">
          <div class="password-header">
            <div class="password-lock-icon">
              <i class="el-icon-unlock"></i>
              <div class="lock-icon-inner">
                <i class="el-icon-lock"></i>
              </div>
            </div>
          </div>
          <div class="password-display">
            <div class="password-title">生成的密码</div>
            <div class="password-digits">
              <span v-for="(digit, i) in periodPassword.split('')" :key="i" class="password-digit">{{digit}}</span>
            </div>
            <div class="password-info">
              <i class="el-icon-time"></i>
              <span>密码在 {{periodStartTime || '选择的开始时间'}} 至 {{periodEndTime || '选择的结束时间'}} 期间有效</span>
            </div>
            <div class="password-remarks" v-if="periodForm.remarks">
              <i class="el-icon-notebook-2"></i>
              <span>备注：{{periodForm.remarks}}</span>
            </div>
            <div class="password-actions">
              <el-button type="primary" @click="resetPeriodForm">继续生成</el-button>
              <el-button @click="periodDialogVisible = false">关闭</el-button>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" v-if="false" class="dialog-footer">
        <el-button v-if="periodPassword" @click="resetPeriodForm">继续生成</el-button>
        <el-button type="primary" @click="periodDialogVisible = false" round>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 临时密码对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
      :show-close="false"
      center
      class="password-dialog-wrapper"
      top="20vh"
    >
      <div slot="title" class="custom-dialog-title">
        <i class="el-icon-key"></i>
        <span>临时密码</span>
      </div>
      <div class="password-dialog">
        <div class="password-header">
          <div class="password-lock-icon">
            <i class="el-icon-unlock"></i>
            <div class="lock-icon-inner">
              <i class="el-icon-lock"></i>
            </div>
          </div>
        </div>
        <div class="password-display">
          <div class="password-digits">
            <template v-if="password">
              <span v-for="(digit, i) in password.split('')" :key="i" class="password-digit">{{digit}}</span>
            </template>
            <template v-else>
              <span class="password-loading">
                <i class="el-icon-loading"></i> 生成中...
              </span>
            </template>
          </div>
          <div class="password-info">
            <i class="el-icon-time"></i>
            <span>密码在 {{formattedEndTime || '获取中...'}} 前仅能使用一次</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false" round>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 远程开门确认对话框 -->
    <el-dialog :visible.sync="remoteOpenOpen" title="远程开门确认" width="400px">
      <div class="remote-open-info">
        <p><i class="el-icon-info"></i> 确认要远程开启以下房间的门锁吗？</p>
        <div class="room-info">
          <strong>房间信息：</strong>
          <span>{{ remoteOpenForm.roomName || '' }}</span>
        </div>
        <div class="device-info">
          <strong>设备信息：</strong>
          <span>{{ remoteOpenForm.deviceName || '智能门锁' }}</span>
        </div>
        <div class="warning-info">
          <i class="el-icon-warning"></i>
          <span>注意：门锁必须联网才能成功执行远程开门操作</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelRemoteOpen">取消</el-button>
        <el-button type="primary" @click="submitRemoteOpen" :loading="remoteOpenLoading">确认开门</el-button>
      </span>
    </el-dialog>

    <!-- 门锁激活Wi-Fi提示对话框 -->
    <el-dialog :visible.sync="activateWifiOpen" title="等待门锁激活Wi-Fi" width="400px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="activate-wifi-info">
        <div class="lock-icon">
          <i class="el-icon-lock"></i>
        </div>
        <div class="instruction-text">
          <p>请先在门锁输入9#激活</p>
          <p>Wi-Fi,激活后APP会自动发</p>
          <p>送命令</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="closeActivateWifi">我知道了</el-button>
      </span>
    </el-dialog>

    <!-- 调试信息 -->
    <div v-if="false" style="position: fixed; bottom: 10px; right: 10px; background: #fff; padding: 10px; border: 1px solid #ddd; z-index: 9999;">
      <pre>{{ JSON.stringify({dialogVisible, password, smartlocksList}, null, 2) }}</pre>
    </div>
  </div>
</template>

<script>
  import { getHome } from "@/api/lock/home";
  import { hxAddSingleKey, listPeriodicPasswords, updatePasswordRemarks } from "@/api/lock/details";
  import { clearAllPasswords, delKeyClearCard } from "@/api/lock/tenantkey";
  // 添加远程开门API导入
  import { remoteOpenLock } from "@/api/lock/remoteOpen";
  import battery from "../battery.vue";

  // 新增的信号强度组件
  const SignalStrength = {
    props: {
      value: {
        type: [Number, String],
        default: 0
      },
      maxBars: {
        type: Number,
        default: 4
      }
    },
    computed: {
      signalBars() {
        // 根据RSSI值计算信号强度条数，通常RSSI在-30到-100之间
        // RSSI值越大（越接近0），信号越强
        const rssi = parseInt(this.value);
        if (!rssi || isNaN(rssi)) return 0;

        if (rssi >= -50) return this.maxBars; // 满格信号
        if (rssi >= -65) return 3;
        if (rssi >= -75) return 2;
        if (rssi >= -85) return 1;
        return 0; // 无信号
      }
    },
    render(h) {
      const bars = [];
      for (let i = 0; i < this.maxBars; i++) {
        bars.push(h('div', {
          class: ['signal-bar', i < this.signalBars ? 'active' : '']
        }));
      }
      return h('div', { class: 'signal-strength-indicator' }, bars);
    }
  };

  export default {
    name: "Smartlocks",
    dicts: ['can_use'],
    components: {
      battery,
      SignalStrength
    },
    data() {
      return {
        lockMac: null, // 存储锁编号给子组件
        // 遮罩层
        loading: true,
        // 刷新状态
        refreshing: false,
        // 智能锁设备信息表格数据
        smartlocksList: [],
        smartList: null,
        dialogVisible: false, // 看房密码对话框
        // 看房密码相关变量
        password: null, // 生成的看房密码
        formattedEndTime: null, // 一次性密码有效期结束时间
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          homeId: null,
          type: null
        },
        // 是否显示高级信息
        showAdvanced: false,
        // 是否显示管理员密码
        showPwd: false,
        periodDialogVisible: false,
        periodPassword: null,
        periodForm: {
          startTime: null,
          endTime: null,
          remarks: ''
        },
        // 表单验证规则
        periodFormRules: {
          startTime: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],
          endTime: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ]
        },
        periodLoading: false,
        periodStartTime: null,
        periodEndTime: null,
        periodPasswords: [],
        showExpiredPasswords: false,
        // 日期选择器配置
        pickerOptions: {
          start: {},
          end: {}
        },
        // 添加日期选择器引用
        datePickerRefs: {
          startTime: null,
          endTime: null
        },
        // 远程开门相关数据
        remoteOpenOpen: false, // 远程开门弹出层
        remoteOpenForm: {}, // 远程开门表单
        remoteOpenLoading: false, // 远程开门加载状态
        // 门锁激活Wi-Fi提示
        activateWifiOpen: false, // 门锁激活Wi-Fi提示弹出层
      };
    },
    created() {
      this.queryParams.homeId = this.$route.query.id;
      this.getList().then(() => {
        // 加载周期性密码列表
        // this.loadPeriodicPasswords();
      });

      // 初始化日期选择器配置 - 使用最简单的原生配置
      const self = this;

      // 开始时间选择器选项 - 保持简单
      this.pickerOptions.start = {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 不允许选择今天以前的日期
        }
      };

      // 结束时间选择器选项 - 保持简单
      this.pickerOptions.end = {
        disabledDate(time) {
          if (!self.periodForm.startTime) return false;
          // 结束时间至少要比开始时间晚1小时
          const startTime = new Date(self.periodForm.startTime).getTime();
          return time.getTime() < startTime + 3600 * 1000;
        }
      };
    },
    mounted() {
      // 添加调试代码
      console.log('Component mounted');

      // 监控日期选择器事件
      this.$nextTick(() => {
        const startPicker = this.$refs.startTimePicker;
        const endPicker = this.$refs.endTimePicker;

        if (startPicker) {
          console.log('Found start picker ref');
        }

        if (endPicker) {
          console.log('Found end picker ref');
        }
      });
    },
    methods: {
      // 判断设备是否在线
      isOnline(lock) {
        // 简单判断：如果最后通讯时间在24小时内，认为是在线
        if (!lock.lastCommunication) return false;
        const lastComm = new Date(lock.lastCommunication).getTime();
        const now = new Date().getTime();
        return (now - lastComm) < 24 * 60 * 60 * 1000;
      },

      // 格式化时间显示
      formatTime(timeStr) {
        if (!timeStr) return '未知';
        // 可以根据需要自定义时间格式化
        try {
          const date = new Date(timeStr);
          return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          });
        } catch (e) {
          return timeStr;
        }
      },

      // 根据电量返回对应的CSS类
      getBatteryClass(level) {
        if (level >= 70) return 'high-battery';
        if (level >= 30) return 'medium-battery';
        return 'low-battery';
      },

      // 根据电量返回对应的卡片颜色类
      getBatteryColorClass(level) {
        if (level >= 70) return 'high-level';
        if (level >= 30) return 'medium-level';
        return 'low-level';
      },

      // 切换高级信息显示状态
      toggleAdvanced() {
        this.showAdvanced = !this.showAdvanced;
      },

      // 刷新锁设备信息
      refreshLockInfo(lock) {
        this.refreshing = true;
        this.getList().finally(() => {
          // setTimeout(() => {
            this.refreshing = false;
          // }, 500);
        });
      },

      // 看房密码相关方法
      hxAddSingleKeyHandel() {
        console.log("按钮被点击");
        this.dialogVisible = true;
        this.password = null; // 先清空密码，显示加载中状态
        this.formattedEndTime = null; // 清空有效期显示

        // 添加延迟以确保对话框已渲染
        this.$nextTick(() => {
          // 防止重复点击
          const generateBtn = document.querySelector('.generate-password-btn');
          if (generateBtn) {
            generateBtn.setAttribute('disabled', 'disabled');
            generateBtn.classList.add('is-loading');
          }

          // 自动生成新密码
          this.hxAddSingleKeyFF().finally(() => {
            // 恢复按钮状态
            setTimeout(() => {
              if (generateBtn) {
                generateBtn.removeAttribute('disabled');
                generateBtn.classList.remove('is-loading');
              }
            }, 1000);
          });
        });
      },

      // 生成一次性密码
      hxAddSingleKeyFF() {
        console.log("尝试生成密码", this.smartlocksList);
        if (this.smartlocksList && this.smartlocksList.length > 0) {
          // 构建正确的参数
          const params = {
            type: 1,
            mac: this.smartlocksList[0].mac,
            homeId: this.queryParams.homeId,
            roomId: this.smartlocksList[0].roomId // 如果设备中有roomId字段
          };

          console.log("发送请求参数:", params);

          return hxAddSingleKey(params).then(response => {
            console.log("密码生成成功:", response);
            if (response.code === 200 && response.data) {
              this.password = response.data.password || response.data.jieMiPassword;
              this.formattedEndTime = response.data.endTime || '24小时内';
              this.$message.success("临时密码生成成功");
            } else {
              this.$message.warning("返回数据格式不正确");
              this.password = "格式错误";
            }
          }).catch(error => {
            console.error("生成密码失败:", error);
            this.$message.error("生成密码失败: " + (error.message || "未知错误"));
            this.password = "生成失败";
          });
        } else {
          this.$message.error("未找到设备信息，无法生成密码");
          this.password = "无法生成";
        }
      },

      handleClose() {
        // 空方法，用于对话框关闭
      },

      /** 查询智能锁设备信息列表 */
      getList() {
        this.loading = true;
        return getHome(this.queryParams.homeId).then(response => {
          if (response && response.data) {
            this.smartlocksList = [response.data];
            if (this.smartlocksList && this.smartlocksList.length > 0) {
              this.lockMac = this.smartlocksList[0].mac;
            }
            this.smartList = this.smartlocksList.map(item => {
              return {
                id: item.mac,
                name: item.remark
              };
            });
          } else {
            this.smartlocksList = [];
          }
          this.loading = false;
        }).catch(error => {
          this.loading = false;
          console.error("获取房间信息失败", error);
        });
      },

      showPeriodPasswordDialog() {
        this.periodDialogVisible = true;
        this.periodPassword = null;

        // 明确清空时间字段并设置为null
        this.$nextTick(() => {
          this.periodForm = {
            startTime: null,
            endTime: null,
            remarks: ''
          };
        });

        this.periodLoading = false;

        // 检查并更新密码状态（是否过期）
        this.updatePasswordsStatus();
      },

      // 更新所有密码的过期状态
      updatePasswordsStatus() {
        const now = new Date();
        this.periodPasswords.forEach(pwd => {
          try {
            // 确保rawEndTime是有效值
            if (!pwd.rawEndTime) {
              pwd.isExpired = false;
              return;
            }

            const endTime = new Date(pwd.rawEndTime);

            // 检查日期是否有效
            if (isNaN(endTime.getTime())) {
              console.error('Invalid end time in password:', pwd);
              pwd.isExpired = false;
              return;
            }

            pwd.isExpired = endTime < now;
          } catch (e) {
            console.error('Error checking password expiry:', e, pwd);
            pwd.isExpired = false; // 默认为未过期
          }
        });

        // 密码按过期状态和创建时间排序：有效的在前，最近创建的在上
        this.periodPasswords.sort((a, b) => {
          if (a.isExpired !== b.isExpired) {
            return a.isExpired ? 1 : -1;
          }

          try {
            const dateA = a.createdAt ? new Date(a.createdAt) : new Date(0);
            const dateB = b.createdAt ? new Date(b.createdAt) : new Date(0);

            if (isNaN(dateA.getTime()) || isNaN(dateB.getTime())) {
              return 0; // 如果日期无效，不改变顺序
            }

            return dateB - dateA;
          } catch (e) {
            console.error('Error sorting passwords:', e);
            return 0; // 发生错误时不改变顺序
          }
        });
      },

      // 从数据库加载密码列表
      loadPeriodicPasswords() {
        if (this.smartlocksList && this.smartlocksList.length > 0) {
          listPeriodicPasswords(
            this.smartlocksList[0].mac,
            this.queryParams.homeId,
            this.showExpiredPasswords
          ).then(response => {
            if (response.code === 200 && Array.isArray(response.data)) {
              // 安全地处理响应数据
              this.periodPasswords = response.data.map(item => {
                // 提供默认值，防止空对象操作
                item = item || {};

                let formattedStartTime = '未知时间';
                let formattedEndTime = '未知时间';

                try {
                  if (item.startTime) {
                    formattedStartTime = this.formatDateTime(item.startTime) || '未知时间';
                  }
                } catch (e) {
                  console.error('Error formatting start time:', e);
                }

                try {
                  if (item.endTime) {
                    formattedEndTime = this.formatDateTime(item.endTime) || '未知时间';
                  }
                } catch (e) {
                  console.error('Error formatting end time:', e);
                }

                return {
                  id: item.id || '',
                  password: item.password || '未知',
                  startTime: formattedStartTime,
                  endTime: formattedEndTime,
                  rawStartTime: item.startTime || '',
                  rawEndTime: item.endTime || '',
                  remarks: item.remarks || '',
                  isExpired: !!item.isExpired, // 确保是布尔值
                  editing: false,
                  createdAt: item.createdAt || ''
                };
              });

              // 更新密码过期状态
              this.updatePasswordsStatus();
            } else {
              this.$message.error("获取周期性密码列表失败: " + (response.msg || "数据格式错误"));
              // 确保periodPasswords始终是数组
              if (!Array.isArray(this.periodPasswords)) {
                this.periodPasswords = [];
              }
            }
          }).catch(error => {
            console.error("获取周期性密码列表失败", error);
            this.$message.error("获取周期性密码列表失败: " + (error.message || String(error)));
            this.periodPasswords = []; // 确保错误时将密码列表重置为空数组
          });
        } else {
          this.periodPasswords = []; // 无设备时设置为空数组
        }
      },

      startEdit(pwd) {
        pwd.editing = true;
      },

      saveRemarks(pwd) {
        pwd.editing = false;

        if (pwd.id) {
          updatePasswordRemarks(pwd.id, pwd.remarks).then(response => {
            if (response.code === 200) {
              this.$message.success("备注更新成功");
            } else {
              this.$message.error("备注更新失败: " + response.msg);
            }
          }).catch(error => {
            console.error("更新备注失败", error);
            this.$message.error("更新备注失败: " + (error.message || error));
          });
        }
      },

      validateTimeRange() {
        if (this.periodForm.startTime && this.periodForm.endTime) {
          try {
            // 确保创建有效的日期对象
            const startTime = new Date(this.periodForm.startTime);
            const endTime = new Date(this.periodForm.endTime);

            // 检查日期是否有效
            if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
              console.error('Invalid date objects:', { startTime, endTime });
              this.$message.warning("日期格式无效，请重新选择");
              return false;
            }

            // 检查开始时间是否小于结束时间
            if (startTime >= endTime) {
              this.$message.warning("开始时间必须小于结束时间");
              this.periodForm.endTime = null;
              return false;
            }

            // 检查时间间隔是否至少为1小时
            const diffMs = endTime.getTime() - startTime.getTime();
            const diffHours = diffMs / (1000 * 60 * 60);

            if (diffHours < 1) {
              this.$message.warning("密码最小间隔为1小时，请检查起止时间");
              // 可以选择清空结束时间或自动调整为开始时间+1小时
              const newEndTime = new Date(startTime.getTime() + 60 * 60 * 1000);
              this.periodForm.endTime = this.formatDateForPicker(newEndTime);
              return false;
            }

            return true;
          } catch (e) {
            console.error('Error in validateTimeRange:', e);
            this.$message.warning("日期处理出错，请重新选择");
            return false;
          }
        }
        return this.periodForm.startTime === null || this.periodForm.endTime === null;
      },

      // 格式化日期为选择器使用的格式
      formatDateForPicker(date) {
        if (!date) return null;

        // 确保date是一个Date对象
        if (!(date instanceof Date)) {
          try {
            // 如果不是Date对象，尝试转换
            date = new Date(date);
            // 检查转换后是否有效
            if (isNaN(date.getTime())) {
              console.error('Invalid date format', date);
              return null;
            }
          } catch (e) {
            console.error('Error converting to date', e);
            return null;
          }
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
      },

      generatePeriodPassword() {
        // 使用表单验证
        this.$refs.periodForm.validate(valid => {
          if (!valid) {
            return;
          }

          // 检查时间间隔是否有效
          if (!this.validateTimeRange()) {
            return;
          }

          this.periodLoading = true;

          if (this.smartlocksList && this.smartlocksList.length > 0) {
            // 构建周期性密码的参数
            const params = {
              type: 2, // 周期性密码类型
              mac: this.smartlocksList[0].mac,
              homeId: this.queryParams.homeId,
              startTime: this.periodForm.startTime,
              endTime: this.periodForm.endTime,
              remarks: this.periodForm.remarks // 添加备注字段
            };

            console.log("发送周期性密码请求参数:", params);

            hxAddSingleKey(params).then(response => {
              console.log("周期性密码生成成功:", response);
              if (response.code === 200 && response.data) {
                // 设置当前新生成的密码
                this.periodPassword = response.data.password || response.data.jieMiPassword;

                // 格式化日期显示，确保即使格式化失败也有默认值
                try {
                  this.periodStartTime = this.formatDateTime(this.periodForm.startTime);
                  if (!this.periodStartTime) {
                    this.periodStartTime = '开始时间';
                  }
                } catch (e) {
                  console.error('Error formatting start time:', e);
                  this.periodStartTime = '开始时间';
                }

                try {
                  this.periodEndTime = this.formatDateTime(this.periodForm.endTime);
                  if (!this.periodEndTime) {
                    this.periodEndTime = '结束时间';
                  }
                } catch (e) {
                  console.error('Error formatting end time:', e);
                  this.periodEndTime = '结束时间';
                }

                // 重新加载周期性密码列表
                this.loadPeriodicPasswords();

                this.$message.success("周期性密码生成成功");
              } else {
                this.$message.error(response.msg || "生成周期性密码失败");
              }
            }).catch(error => {
              console.error("生成周期性密码失败", error);
              this.$message.error("生成周期性密码失败: " + (error.message || error));
            }).finally(() => {
              this.periodLoading = false;
            });
          } else {
            this.$message.error("未找到智能锁设备");
            this.periodLoading = false;
          }
        });
      },

      // 日期格式化
      formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '';

        try {
          const date = new Date(dateTimeStr);

          // 检查日期是否有效
          if (isNaN(date.getTime())) {
            console.error('Invalid date format in formatDateTime:', dateTimeStr);
            return dateTimeStr; // 返回原始字符串，避免显示错误
          }

          return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        } catch (e) {
          console.error('Error formatting date:', e, dateTimeStr);
          return dateTimeStr; // 返回原始字符串，避免显示错误
        }
      },

      resetPeriodForm() {
        this.periodPassword = null;
        this.periodForm.startTime = null;
        this.periodForm.endTime = null;
        this.periodForm.remarks = '';
        this.periodLoading = false;
      },

      // 刷新周期性密码列表
      refreshPeriodicPasswords() {
        this.loadPeriodicPasswords();
      },

      // 确认清除密码
      confirmClearPassword() {
        this.$confirm('确认清除该智能锁的所有密码吗？此操作不可逆，密码将被永久删除。', '警告', {
          confirmButtonText: '确认清除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.execClearAllPasswords();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消清除操作'
          });
        });
      },

      // 清除所有密码
      execClearAllPasswords() {
        this.loading = true;

        if (!this.smartlocksList || this.smartlocksList.length === 0) {
          this.$message.error('未找到设备信息');
          this.loading = false;
          return;
        }

        // 获取当前锁的mac地址
        const mac = this.smartlocksList[0].mac;

        // 调用清除密码接口，使用mac参数
        clearAllPasswords(mac).then(res => {
          if (res.code === 200) {
            this.$message.success('密码清除任务已下发，请等待设备处理');
            // 刷新锁信息
            setTimeout(() => {
              this.refreshLockInfo(this.smartlocksList[0]);
            }, 1000);
          } else {
            this.$message.error(res.msg || '清除密码失败');
          }
          this.loading = false;
        }).catch(err => {
          console.error('清除密码请求失败:', err);
          this.$message.error('清除密码请求失败');
          this.loading = false;
        });
      },

      // 确认清除卡片
      confirmClearCard() {
        this.$confirm('确认清除该智能锁的所有卡片吗？此操作不可逆，卡片将被永久删除。', '警告', {
          confirmButtonText: '确认清除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.execClearCard();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消清除卡片操作'
          });
        });
      },

      // 执行清除卡片
      execClearCard() {
        this.loading = true;

        if (!this.smartlocksList || this.smartlocksList.length === 0) {
          this.$message.error('未找到设备信息');
          this.loading = false;
          return;
        }

        // 获取当前锁的mac地址
        const mac = this.smartlocksList[0].mac;

        // 调用清除卡片接口，使用mac参数
        delKeyClearCard(mac).then(res => {
          if (res.code === 200) {
            this.$message.success('卡片清除任务已下发，请等待设备处理');
            // 刷新锁信息
            setTimeout(() => {
              this.refreshLockInfo(this.smartlocksList[0]);
            }, 1000);
          } else {
            this.$message.error(res.msg || '清除卡片失败');
          }
          this.loading = false;
        }).catch(err => {
          console.error('清除卡片请求失败:', err);
          this.$message.error('清除卡片请求失败');
          this.loading = false;
        });
      },

      // 远程开门相关方法
      /** 远程开门按钮操作 */
      handleRemoteOpen(lock) {
        console.log("远程开门按钮点击, 设备信息:", lock);
        this.remoteOpenForm = {
          roomNum: lock.roomNum,
          roomName: lock.roomName || '未知房间',
          deviceName: lock.deviceName || '智能门锁',
          mac: lock.mac
        };
        console.log("设置到远程开门表单的数据:", this.remoteOpenForm);
        this.remoteOpenOpen = true;
      },

      /** 提交远程开门 */
      submitRemoteOpen() {
        this.remoteOpenLoading = true;

        // 构建请求参数
        const requestData = {
          roomNum: this.remoteOpenForm.roomNum
        };

        remoteOpenLock(requestData).then(response => {
          this.remoteOpenLoading = false;

          if (response.resultCode === 0) {
            this.$modal.msgSuccess("远程开门指令发送成功");
            this.remoteOpenOpen = false;

            // 记录开门日志
            this.recordOpenLog("远程开门");
          } else {
            // 根据错误码显示不同的错误信息
            let errorMsg = "远程开门失败";
            switch (response.resultCode) {
              case 500001:
                errorMsg = "参数异常";
                break;
              case 500002:
                errorMsg = "不支持该类型的门锁";
                break;
              case 500003:
                errorMsg = "房间不存在";
                break;
              case 500004:
                // 门锁需要激活Wi-Fi，显示激活提示弹窗
                this.remoteOpenOpen = false; // 关闭远程开门确认弹窗
                this.activateWifiOpen = true; // 显示激活Wi-Fi提示弹窗
                return; // 直接返回，不显示错误消息
              default:
                errorMsg = response.reason || "远程开门失败";
            }
            this.$modal.msgError(errorMsg);
          }
        }).catch(error => {
          this.remoteOpenLoading = false;
          console.error("远程开门失败:", error);
          this.$modal.msgError("远程开门失败，请检查网络连接");
        });
      },

      /** 取消远程开门 */
      cancelRemoteOpen() {
        this.remoteOpenOpen = false;
        this.remoteOpenForm = {};
      },

      /** 记录开门日志 */
      recordOpenLog(openType) {
        // 这里可以调用开门日志记录接口
        console.log(`记录${openType}日志:`, this.remoteOpenForm);
      },

      /** 关闭激活Wi-Fi提示弹窗 */
      closeActivateWifi() {
        this.activateWifiOpen = false;
      },
    }
  };
</script>

<style scoped lang="scss">
  .app-container {
    padding: 0;
  }

  .smart-lock-container {
    padding: 0;
  }

  .lock-card {
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 6px 30px rgba(24, 144, 255, 0.15);
      transform: translateY(-2px);
    }
  }

  .lock-header {
    display: flex;
    align-items: center;
    padding: 20px;
    background: linear-gradient(135deg, #1890ff, #096dd9);
    color: white;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: -40px;
      right: -40px;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
    }

    &::after {
      content: '';
      position: absolute;
      bottom: -30px;
      left: -30px;
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.05);
    }

    .lock-icon-wrapper {
      position: relative;
      margin-right: 20px;

      .lock-icon {
        width: 60px;
        height: 60px;
        background: radial-gradient(circle at center, #2589ff, #0057d0);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        box-shadow: 0 4px 15px rgba(24, 144, 255, 0.3), inset 0 2px 5px rgba(255, 255, 255, 0.3);
        overflow: hidden;

        /* 外部图标 - 门框 */
        .el-icon-unlock {
          position: absolute;
          font-size: 40px;
          color: rgba(255, 255, 255, 0.9);
          transform: scale(1.2);
          z-index: 1;
        }

        /* 内部图标 - 钥匙孔动画 */
        .lock-icon-inner {
          position: absolute;
          width: 25px;
          height: 25px;
          background: rgba(255, 255, 255, 0.15);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          animation: pulse 2s infinite ease-in-out;

          .el-icon-lock {
            font-size: 14px;
            color: white;
          }
        }

        &::before {
          content: '';
          position: absolute;
          top: -10px;
          left: -10px;
          right: -10px;
          bottom: -10px;
          border-radius: 50%;
          background: linear-gradient(45deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 60%);
          transform: rotate(45deg);
        }

        &::after {
          content: '';
          position: absolute;
          width: 100%;
          height: 100%;
          border-radius: 50%;
          background: radial-gradient(circle at 70% 70%, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 60%);
        }
      }

      .lock-status-indicator {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 14px;
        height: 14px;
        border-radius: 50%;
        border: 2px solid white;

        &.online {
          background-color: #52c41a;
        }

        &.offline {
          background-color: #f5222d;
        }
      }
    }

    .lock-title {
      flex: 1;
      display: flex;
      flex-direction: column;
      z-index: 1;

      .device-name {
        font-size: 22px;
        font-weight: 600;
        margin-bottom: 8px;
      }

      .device-info {
        display: flex;
        align-items: center;

        .device-mac {
          font-size: 14px;
          opacity: 0.9;
          margin-right: 10px;
        }

        .status-tag {
          margin-left: 5px;
        }
      }
    }

    .header-actions {
      z-index: 1;

      .refresh-btn {
        color: white;
        font-size: 18px;
        transition: all 0.3s;

        &.rotate {
          animation: rotating 1s linear infinite;
        }

        &:hover {
          transform: scale(1.2);
        }
      }
    }
  }

  .lock-info-content {
    padding: 20px;
  }

  .info-section {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin-bottom: 20px;
  }

  .metric-card {
    background-color: #f9f9f9;
    border-radius: 10px;
    padding: 15px;
    display: flex;
    align-items: center;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .metric-icon-wrapper {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;

      .metric-icon {
        font-size: 20px;
        color: white;
      }
    }

    .metric-content {
      flex: 1;

      .metric-title {
        font-size: 13px;
        color: #606266;
        margin-bottom: 5px;
      }

      .metric-value-wrapper {
        display: flex;
        align-items: center;

        .metric-value {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }

      .metric-value {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    &.battery-card {
      &.high-level {
        background-color: rgba(82, 196, 26, 0.1);

        .metric-icon-wrapper {
          background-color: #52c41a;
        }

        .metric-value {
          color: #52c41a;
        }
      }

      &.medium-level {
        background-color: rgba(250, 173, 20, 0.1);

        .metric-icon-wrapper {
          background-color: #faad14;
        }

        .metric-value {
          color: #faad14;
        }
      }

      &.low-level {
        background-color: rgba(245, 34, 45, 0.1);

        .metric-icon-wrapper {
          background-color: #f5222d;
        }

        .metric-value {
          color: #f5222d;
        }
      }

      .battery-indicator {
        margin-right: 5px;
      }
    }

    &.signal-card {
      background-color: rgba(24, 144, 255, 0.1);

      .metric-icon-wrapper {
        background-color: #1890ff;
      }

      .metric-value {
        color: #1890ff;
      }
    }

    &.voltage-card {
      background-color: rgba(114, 46, 209, 0.1);

      .metric-icon-wrapper {
        background-color: #722ed1;
      }

      .metric-value {
        color: #722ed1;
      }
    }
  }

  .info-divider {
    display: flex;
    align-items: center;
    margin: 20px 0;

    &::before, &::after {
      content: '';
      flex: 1;
      height: 1px;
      background-color: #ebeef5;
    }

    .divider-text {
      padding: 0 15px;
      font-size: 14px;
      color: #909399;
      white-space: nowrap;
    }
  }

  .details-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    margin-bottom: 20px;
    overflow: hidden;
    max-height: 140px;
    transition: max-height 0.5s ease;
  }

  /* 当showAdvanced为true时展开详情 */
  .details-grid.expanded {
    max-height: 1000px;
  }

  .detail-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border-radius: 8px;
    background-color: #f9f9f9;
    transition: all 0.3s ease;

    &:hover {
      background-color: #f0f7ff;
    }

    .detail-icon {
      width: 36px;
      height: 36px;
      border-radius: 8px;
      background-color: rgba(24, 144, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;

      i {
        font-size: 18px;
        color: #1890ff;
      }
    }

    .detail-content {
      flex: 1;

      .detail-label {
        font-size: 13px;
        color: #909399;
        margin-bottom: 4px;
      }

      .detail-value {
        font-size: 14px;
        color: #303133;
        word-break: break-all;

        &.pwd-value {
          display: flex;
          align-items: center;

          .toggle-pwd-btn {
            margin-left: 8px;
            padding: 2px 5px;
            font-size: 12px;
            color: #1890ff;

            &:hover {
              color: #40a9ff;
              background-color: rgba(24, 144, 255, 0.1);
            }
          }
        }
      }
    }

    /* 管理员密码相关样式 */
    &:nth-child(3) {
      background-color: #f6f8ff;
      border-left: 3px solid #1890ff;

      .detail-icon {
        background-color: rgba(64, 158, 255, 0.2);

        i {
          color: #1890ff;
          font-weight: bold;
        }
      }

      .detail-label {
        color: #1890ff;
        font-weight: 600;
      }

      .detail-value {
        font-family: monospace;
        font-weight: 600;
        letter-spacing: 1px;
      }
    }
  }

  .lock-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;

    .advanced-toggle {
      display: flex;
      align-items: center;
      cursor: pointer;
      color: #909399;
      font-size: 14px;
      transition: all 0.3s ease;
      background: #f5f7fa;
      padding: 6px 12px;
      border-radius: 4px;

      i {
        margin-left: 5px;
      }

      &:hover {
        color: #1890ff;
        background: #ecf5ff;
      }
    }

    .buttons-row {
      display: flex;
      gap: 8px;
      align-items: center;

      .action-btn {
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        white-space: nowrap;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(255,255,255,0) 100%);
          pointer-events: none;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        &:active {
          transform: translateY(1px);
        }

        i {
          margin-right: 4px;
        }
      }

      .danger-btn {
        background-color: #f56c6c;
        border-color: #f56c6c;
        color: white;

        &:hover {
          background-color: #f78989;
          border-color: #f78989;
          box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
        }
      }
    }
  }

  /* 临时密码对话框样式 */
  .password-dialog-wrapper {
    ::v-deep .el-dialog {
      overflow: hidden;
      border-radius: 10px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
    }

    ::v-deep .el-dialog__header {
      background: linear-gradient(135deg, #1890ff, #096dd9);
      padding: 15px 20px;
      border-radius: 10px 10px 0 0;
      margin-bottom: 0;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        top: -30px;
        right: -30px;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.1);
      }
    }

    ::v-deep .el-dialog__body {
      padding: 25px 20px 15px;
      background: linear-gradient(180deg, #f9fbfe, #f0f7ff);
    }

    ::v-deep .el-dialog__footer {
      padding: 10px 20px 20px;
      background: linear-gradient(180deg, #f0f7ff, #f9fbfe);
      border-top: none;
    }

    ::v-deep .el-button--primary {
      background: linear-gradient(135deg, #1890ff, #096dd9);
      border-color: #096dd9;
      padding: 10px 30px;
      font-size: 16px;
      transition: all 0.3s ease;

      &:hover, &:focus {
        background: linear-gradient(135deg, #40a9ff, #1890ff);
        border-color: #1890ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
      }
    }

    .custom-dialog-title {
      display: flex;
      align-items: center;

      span {
        color: white;
        font-size: 18px;
        font-weight: 500;
      }

      i {
        color: white;
        font-size: 22px;
        margin-right: 10px;
      }
    }
  }

  .password-dialog {
    padding: 0;

    .password-header {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;

      .password-lock-icon {
        width: 80px;
        height: 80px;
        background: radial-gradient(circle at center, #2589ff, #0057d0);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 8px 20px rgba(24, 144, 255, 0.3), inset 0 2px 5px rgba(255, 255, 255, 0.3);
        position: relative;
        overflow: hidden;

        .el-icon-unlock {
          position: absolute;
          font-size: 50px;
          color: rgba(255, 255, 255, 0.9);
          transform: scale(1.2);
          z-index: 1;
        }

        .lock-icon-inner {
          position: absolute;
          width: 30px;
          height: 30px;
          background: rgba(255, 255, 255, 0.15);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          animation: pulse 2s infinite ease-in-out;

          .el-icon-lock {
            font-size: 16px;
            color: white;
          }
        }

        &::before {
          content: '';
          position: absolute;
          top: -10px;
          left: -10px;
          right: -10px;
          bottom: -10px;
          border-radius: 50%;
          background: linear-gradient(45deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 60%);
          transform: rotate(45deg);
        }

        &::after {
          content: '';
          position: absolute;
          width: 100%;
          height: 100%;
          border-radius: 50%;
          background: radial-gradient(circle at 70% 70%, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 60%);
        }
      }
    }

    .password-display {
      .password-digits {
        display: flex;
        justify-content: center;
        flex-wrap: nowrap;
        overflow-x: auto;
        margin-bottom: 20px;
        padding: 10px 0;

        .password-digit {
          width: 45px;
          height: 55px;
          margin: 0 4px;
          flex-shrink: 0;
          background-color: #f5f7fa;
          border-radius: 10px;
          font-size: 26px;
          font-weight: bold;
          color: #303133;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(24, 144, 255, 0.15);
            background-color: #ecf5ff;
            color: #1890ff;
          }
        }

        .password-loading {
          font-size: 16px;
          color: #1890ff;
          padding: 12px 20px;
          background: rgba(24, 144, 255, 0.05);
          border-radius: 10px;
          display: inline-flex;
          align-items: center;
          white-space: nowrap;

          i {
            margin-right: 8px;
            font-size: 20px;
            animation: rotating 1.5s linear infinite;
          }
        }
      }

      .password-info {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 15px;
        padding: 12px 15px;
        background: linear-gradient(135deg, rgba(24, 144, 255, 0.1), rgba(24, 144, 255, 0.05));
        border-radius: 20px;
        border: 1px solid rgba(24, 144, 255, 0.1);
        box-shadow: 0 3px 8px rgba(24, 144, 255, 0.05);

        i {
          color: #1890ff;
          margin-right: 10px;
          font-size: 18px;
          flex-shrink: 0;
        }

        span {
          color: #606266;
          font-size: 15px;
          text-align: center;
        }
      }
    }
  }

  .dialog-footer {
    text-align: center;
    margin-top: 10px;
  }

  /* 信号强度样式 */
  .signal-strength-indicator {
    display: flex;
    align-items: flex-end;
    height: 16px;
    margin-right: 8px;

    .signal-bar {
      width: 4px;
      margin: 0 1px;
      background-color: #dcdfe6;
      border-radius: 1px;

      &:nth-child(1) {
        height: 25%;
      }

      &:nth-child(2) {
        height: 50%;
      }

      &:nth-child(3) {
        height: 75%;
      }

      &:nth-child(4) {
        height: 100%;
      }

      &.active {
        background-color: #67c23a;
      }
    }
  }

  /* 动画 */
  @keyframes rotating {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  @keyframes pulse {
    0% {
      transform: scale(0.95);
      box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.3);
    }

    70% {
      transform: scale(1);
      box-shadow: 0 0 0 6px rgba(255, 255, 255, 0);
    }

    100% {
      transform: scale(0.95);
      box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
    }
  }

  .password-btn {
    margin-right: 8px;

    &:last-child {
      margin-right: 0;
    }
  }

  .period-form {
    padding: 25px 35px 30px;
    margin: 20px 0;
    background-color: #f9fbff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .section-title {
      margin-bottom: 25px;
      font-size: 17px;
    }

    .time-selection-area {
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 25px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    }

    .el-form-item {
      margin-bottom: 25px;

      &:last-child {
        margin-bottom: 0;
        margin-top: 30px;
      }

      ::v-deep .el-form-item__label {
        font-weight: 500;
        color: #303133;
        padding-right: 15px;
      }

      ::v-deep .el-form-item__content {
        line-height: 40px;
      }

      .form-tip {
        line-height: 1.4;
        font-size: 12px;
        color: #909399;
        margin-top: 5px;
      }
    }

    ::v-deep .el-input {
      .el-input__inner {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
      }
    }

    /* ElementUI 日期选择器样式优化 */
    ::v-deep .el-date-editor {
      width: 100%;

      .el-input__inner {
        height: 40px;
        line-height: 40px;
        padding-left: 35px;
      }

      .el-input__prefix {
        left: 8px;
      }
    }
  }

  /* 日期选择面板样式 */
  ::v-deep .el-picker-panel {
    /* 增强面板样式 */
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15) !important;
    border-radius: 8px !important;

    .el-button {
      padding: 10px 18px;
      font-size: 14px;
      border-radius: 4px;
      margin-left: 10px;
    }

    .el-date-picker__header {
      margin: 12px 15px 8px;
    }

    .el-picker-panel__content {
      margin: 0 15px 15px;
    }

    .el-date-picker__footer {
      padding: 12px 15px;
      text-align: right;
      border-top: 1px solid #f0f0f0;

      .el-button--text {
        color: #1890ff;
        font-weight: 500;
        padding: 10px 15px;
        margin-left: 0;

        &:hover {
          color: #40a9ff;
          background-color: #f0f7ff;
        }
      }

      .el-button--default {
        border-color: #1890ff;
        color: #1890ff;
        padding: 10px 20px;

        &:hover, &:focus {
          background-color: #ecf5ff;
          border-color: #1890ff;
          color: #1890ff;
        }
      }

      /* 增强确定按钮样式 */
      .el-button--primary {
        background-color: #1890ff !important;
        border-color: #1890ff !important;
        color: white !important;
        font-weight: 600 !important;
        min-width: 85px;
        padding: 12px 24px !important;
        font-size: 15px;
        margin-left: 15px;
        cursor: pointer !important;

        &:hover, &:focus {
          background-color: #40a9ff !important;
          border-color: #40a9ff !important;
          color: white !important;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
          transform: translateY(-1px);
        }
      }
    }

    .el-picker-panel__sidebar {
      width: 130px;

      .el-picker-panel__shortcut {
        padding: 12px 10px;
        font-size: 14px;

        &:hover {
          background-color: #ecf5ff;
          color: #1890ff;
        }
      }
    }

    /* 强调时间选择确认区域 */
    .el-time-panel__footer {
      text-align: right;
      padding: 12px 15px !important;
      margin-top: 5px;
      border-top: 1px solid #f0f0f0;

      .confirm {
        color: white !important;
        font-weight: 600 !important;
        border-radius: 4px !important;
        background-color: #1890ff !important;
        padding: 10px 24px !important;
        font-size: 15px !important;
        min-width: 80px !important;
        cursor: pointer !important;

        &:hover {
          background-color: #40a9ff !important;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3) !important;
          transform: translateY(-1px);
        }
      }

      .cancel {
        padding: 8px 16px !important;
        font-size: 14px !important;
        margin-right: 10px !important;

        &:hover {
          color: #1890ff !important;
          background-color: #f0f7ff !important;
        }
      }
    }
  }

  .form-buttons {
    margin-top: 20px;
    text-align: center;

    .el-button {
      min-width: 120px;
      margin: 0 15px;
      padding: 10px 20px;
      height: auto;
      font-size: 15px;
    }
  }

  .password-dialog-wrapper {
    .el-dialog__body {
      padding-top: 0;
    }

    .custom-dialog-title {
      text-align: center;
      font-size: 20px;
      margin-bottom: 10px;

      i {
        margin-right: 8px;
        font-size: 18px;
      }
    }

    .password-dialog {
      padding: 15px 0;
    }
  }

  .period-passwords-list {
    margin-bottom: 20px;
  }

  .section-title {
    margin: 0 0 15px;
    font-size: 16px;
    color: #303133;
    font-weight: 500;
    position: relative;
    padding-left: 12px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: #1890ff;
      border-radius: 2px;
    }
  }

  .divider-line {
    height: 1px;
    background: #ebeef5;
    margin: 20px 0;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 6px;
      height: 6px;
      background: #ebeef5;
      border-radius: 50%;
    }
  }

  .password-remarks {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 10px;
    padding: 8px 15px;
    background: rgba(103, 194, 58, 0.1);
    border-radius: 20px;
    border: 1px solid rgba(103, 194, 58, 0.2);

    i {
      color: #67c23a;
      margin-right: 10px;
      font-size: 16px;
      flex-shrink: 0;
    }

    span {
      color: #606266;
      font-size: 14px;
      text-align: center;
    }
  }

  /* 添加新样式 */
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .editable-cell {
    min-height: 28px;
    line-height: 28px;
    padding: 0 5px;
    cursor: pointer;
    color: #606266;

    &:hover {
      background-color: #f5f7fa;
      border-radius: 3px;
    }

    &:empty::before {
      content: '点击添加备注';
      color: #999;
      font-style: italic;
    }
  }

  .generated-password {
    padding: 0 20px;

    .password-title {
      text-align: center;
      font-size: 16px;
      color: #303133;
      font-weight: 500;
      margin-bottom: 15px;
    }

    .password-actions {
      margin-top: 20px;
      text-align: center;

      .el-button {
        min-width: 100px;
        margin: 0 10px;
      }
    }
  }

  /* 远程开门对话框样式 */
  .remote-open-info {
    padding: 20px 0;

    p {
      margin: 0 0 20px 0;
      font-size: 16px;
      color: #303133;
      text-align: center;

      i {
        color: #409EFF;
        margin-right: 8px;
      }
    }

    .room-info, .device-info {
      margin-bottom: 15px;
      padding: 10px 15px;
      background: #f5f7fa;
      border-radius: 4px;

      strong {
        color: #606266;
        margin-right: 10px;
      }

      span {
        color: #303133;
        font-weight: 500;
      }
    }

    .warning-info {
      margin-top: 20px;
      padding: 15px;
      background: #fdf6ec;
      border: 1px solid #faecd8;
      border-radius: 4px;
      color: #e6a23c;

      i {
        margin-right: 8px;
        color: #e6a23c;
      }
    }
  }

  /* 禁用按钮样式 */
  .button-disabled {
    color: #c0c4cc !important;
    cursor: not-allowed !important;
    opacity: 0.7 !important;
  }

  /* 门锁激活Wi-Fi提示弹窗样式 */
  .activate-wifi-info {
    text-align: center;
    padding: 20px 0;

    .lock-icon {
      margin: 20px 0;
      font-size: 48px;
      color: #67c23a;
    }

    .instruction-text {
      margin: 20px 0;

      p {
        margin: 8px 0;
        color: #606266;
        font-size: 14px;
        line-height: 1.5;
      }
    }
  }

  /* Responsive adjustments */
  @media (max-width: 768px) {
    .lock-actions {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;

      .buttons-row {
        width: 100%;
        flex-wrap: wrap;

        .action-btn {
          flex: 1;
          min-width: calc(50% - 4px); /* Two buttons per row on small screens */
        }
      }
    }
  }

  @media (max-width: 576px) {
    .buttons-row .action-btn {
      flex: 1 0 100%; /* One button per row on very small screens */
    }
  }
</style>

